package com.hexinfo.dmpro.dev.data.transfer.common.conf;

import com.hexinfo.dmpro.dev.data.transfer.common.constants.AsyncTaskConstants;
import com.hexinfo.dmpro.dev.data.transfer.common.constants.DevDataBuildListAsyncConstants;
import com.hexinfo.dmpro.dev.data.transfer.common.constants.DevDataTransferAsyncConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync()
public class DevDataTransferAsyncTaskPoolConfig {

    private DevDataTransferAsyncConstants devDataTransferAsyncConstants;

    private DevDataBuildListAsyncConstants devDataBuildListAsyncConstants;

    @Autowired(required = false)
    public DevDataTransferAsyncTaskPoolConfig(DevDataTransferAsyncConstants devDataTransferAsyncConstants,
                                              DevDataBuildListAsyncConstants devDataBuildListAsyncConstants) {
        this.devDataTransferAsyncConstants = devDataTransferAsyncConstants;
        this.devDataBuildListAsyncConstants = devDataBuildListAsyncConstants;
    }


    @Bean(name = "devDataTransferAsyncTaskExecutor")
    public Executor devDataTransferAsyncTaskExecutor() {
        return initExecutor(devDataTransferAsyncConstants, "devDataTransferAsyncTaskExecutor-");
    }

    @Bean(name = "devDataBuildListAsyncTaskExecutor")
    public Executor devDataBuildListAsyncTaskExecutor() {
        return initExecutor(devDataBuildListAsyncConstants, "devDataBuildListAsyncTaskExecutor-");
    }

    //初始化方法
    private ThreadPoolTaskExecutor initExecutor(AsyncTaskConstants asyncTaskConstants, String prefix) {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(asyncTaskConstants.getCorePoolSize());
        threadPoolTaskExecutor.setMaxPoolSize(asyncTaskConstants.getMaxPoolSize());
        threadPoolTaskExecutor.setQueueCapacity(asyncTaskConstants.getQueueCapacity());
        threadPoolTaskExecutor.setKeepAliveSeconds(asyncTaskConstants.getKeepAliveSeconds());
        threadPoolTaskExecutor.setThreadNamePrefix(prefix);
        // 线程池对拒绝任务(无线程可用)的处理策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolTaskExecutor;
    }
}
